﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/
using System;
using System.IO;
using Caliburn.Micro;
using ISC.MapDotNetServer.Common.Maps;
using ISC.RIM.Silverlight;
using ISC.RIM.Silverlight.MDNSMapService;
using OI.Framework;
using Map = ISC.MapDotNetServer.Common.Maps.Map;

namespace OI.Async
{
    public class MDNGetLegendIcon : IResult
    {
        // mdn map service proxy
        protected MapServiceClient Client
        {
            get
            {
                return _Client ?? (_Client = ServiceClients.CreateLegendIconServiceClient(GetLegendIconCompleted));
            }
        }
        private MapServiceClient _Client;

        public Map Map { get; private set; }
        public string LayerID { get; private set; }
        public string ClassID { get; private set; }
        public double Scale { get; private set; }
        public int Size { get; private set; }

        // bitmap stream source result
        public MemoryStream Results { get; private set; }

        // constructor
        public MDNGetLegendIcon(Map map, string layerID, string classID, double scale, int size)
        {
            Map = map;
            LayerID = layerID;
            ClassID = classID;
            Scale = scale;
            Size = size;
        }


        // begin the call to gettinga legend icon
        // this approach supports dynamically modified map legends at runtime
        public void Execute(ActionExecutionContext context)
        {
            // layers must be visible when fetching icons
            var layer = Map.GetLayerByID(LayerID);
            bool layVis = layer.Visible;
            layer.Visible = true;

            var mapRequest = new MapRequest {ImageType = MapRequest.SupportedImageTypes.PNG, Map = Map};
            string serialMapRequest = mapRequest.Serialize(true);

            // restore
            layer.Visible = layVis;

            Client.GetLegendIconAsync(Map.ID,
                serialMapRequest, 
                LayerID, 
                ClassID, 
                Scale, 
                Size, 
                Size);
        }


        void GetLegendIconCompleted(object sender, GetLegendIconCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    // result is a serialized MapResponse
                    MapResponse response = MapResponse.Deserialize(e.Result);

                    if (string.IsNullOrEmpty(response.Error) &&
                        response.ImageArray != null)
                    {
                        var ms = new MemoryStream(response.ImageArray);
                        Results = ms;
                    }
                }
            }
            catch(Exception ex)
            {
                HandleError(ex);
            }
            finally
            {
                Completed(this, new ResultCompletionEventArgs());
            }
        }

        // forward error to IShell
        static void HandleError(Exception ex)
        {
            IoC.Get<IShell>().HandleException(ex, "Get legend icon error:");
        }

        public event System.EventHandler<ResultCompletionEventArgs> Completed;
    }
}
